<?php

namespace yifang\console\output\driver;

use yifang\console\Output;

class Console
{
    private $stdout;

    private $formatter;

    private $terminalDimensions;

    private $output;

    public function __construct(Output $output)
    {
        $this->output    = $output;
        $this->stdout    = $this->openOutputStream();
    }

    /**
     * 当前环境是否支持写入控制台输出到stdout.
     *
     * @return bool
     */
    protected function hasStdoutSupport()
    {
        return false === $this->isRunningOS400();
    }

    private function isRunningOS400()
    {
        $checks = [
            function_exists('php_uname') ? php_uname('s') : '',
            getenv('OSTYPE'),
            PHP_OS,
        ];
        return false !== stripos(implode(';', $checks), 'OS400');
    }

    /**
     * @return resource
     */
    private function openOutputStream()
    {
        if (!$this->hasStdoutSupport()) {
            return fopen('php://output', 'w');
        }
        return @fopen('php://stdout', 'w') ?: fopen('php://output', 'w');
    }

    /**
     * 写入数据
     */
    public function write($messages,$newline = false,$type = 0, $stream = null)
    {
        if (Output::VERBOSITY_QUIET === $this->output->getVerbosity()) {
            return;
        }
        $messages = (array) $messages;
        foreach ($messages as $message) {
            $this->doWrite($message, $newline, $stream);
        }
    }

    /**
     * 将消息写入到输出。
     */
    protected function doWrite($message, $newline, $stream = null)
    {
        if (null === $stream) {
            $stream = $this->stdout;
        }
        if (false === @fwrite($stream, $message . ($newline ? PHP_EOL : ''))) {
            throw new \RuntimeException('Unable to write output.');
        }
        fflush($stream);
    }
}